package com.niit.typehandler;


import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

public class ListTypeHandler extends BaseTypeHandler<List<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> hobbies, JdbcType jdbcType) throws SQLException {
        // 把List<String> 转换成  数据库字符串 set到 ps的sql语句中 TODO StringBuilder StringBuffer
        String strHobbies = "";

        for(String hobby : hobbies){
            strHobbies=strHobbies+hobby+";";
        }

        ps.setString(i,strHobbies);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 把查询结果中的字符串：吃饭;睡觉;打豆豆; ===> 转换成 List<String>
        String strHobbies = rs.getString(columnName); // 按照列名获取结果集某列数据
        String[] arrayHobbies = strHobbies.split(";");
        List<String> listHobbies = Arrays.asList(arrayHobbies);
        return listHobbies;
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        // 把查询结果中的字符串：吃饭;睡觉;打豆豆; ===> 转换成 List<String>
        String strHobbies = rs.getString(columnIndex); // 按照index获取结果集某列数据
        String[] arrayHobbies = strHobbies.split(";");
        List<String> listHobbies = Arrays.asList(arrayHobbies);
        return listHobbies;
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return null;
    }
}
